package com.pomelo.tiku.frgs

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.pomelo.tiku.constants.UrlConstants
import kotlinx.android.synthetic.main.fragment_user.view.*
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.pomelo.tiku.activities.RegisterActivity
import com.pomelo.tiku.beans.LoginBean
import com.pomelo.tiku.constants.SharePreferenceConstants
import com.pomelo.tiku.impls.LoginModel
import com.pomelo.tiku.impls.LoginPresenter
import com.pomelo.tiku.interfaces.Contract
import com.pomelo.tiku.managers.SharedPreferenceManager
import com.pomelo.tiku.views.CommonToast
import kotlinx.android.synthetic.main.activity_login.view.*
import kotlinx.android.synthetic.main.fragment_user.*
import java.lang.ref.WeakReference

import android.content.DialogInterface
import android.os.Handler
import android.os.Looper
import android.view.KeyEvent
import androidx.appcompat.app.AlertDialog
import com.blankj.utilcode.util.LogUtils
import com.pomelo.tiku.R
import com.pomelo.tiku.activities.MainActivity
import com.pomelo.tiku.beans.ResponseData
import com.pomelo.tiku.http.OkHttpProcessor
import com.pomelo.tiku.interfaces.IHttpCallBack
import com.pomelo.tiku.utils.GsonUtil


class FragmentUser : BaseFragment(){
    private var mView: View? = null
    private var isLogin = false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initUserInfo()
        if(isLogin) {
            mView = inflater.inflate(R.layout.fragment_user, container, false)
            initViewWithLogin(mView!!)
        } else {
            mView = inflater.inflate(R.layout.activity_login, container, false)
            initViewWithoutLogin(mView!!)
        }
        return mView
    }

    private fun initUserInfo() {
        isLogin = SharedPreferenceManager.getInstance(context).get(SharePreferenceConstants.KEY_ISLOGIN,false) as Boolean
    }
    /**
     * 加载已经登录的界面
     */
    private fun initViewWithLogin(view: View) {
        //Glide设置图片圆角角度
        Glide.with(this).load(R.mipmap.test).apply(
            RequestOptions()
                .transforms(
                    CenterCrop(), RoundedCorners(90)
                )).into(view.img_user_headpic)

        view!!.img_setting.setOnClickListener {
            (activity as MainActivity).showLoading()
             Handler(Looper.getMainLooper()).postDelayed({
                 SharedPreferenceManager.getInstance(context).save(SharePreferenceConstants.KEY_ISLOGIN,false)
                 (activity as MainActivity).reLoadFragView()
                 (activity as MainActivity).stopLoading()
             },500)

        }
    }

    /**
     * 加载没有登录的界面
     */
    private fun initViewWithoutLogin(view: View) {
        view!!.txt_register_now.setOnClickListener {
            startActivity(Intent(this.context,RegisterActivity::class.java))
        }
        view!!.btn_login.setOnClickListener {
            val username = view!!.txt_user_name.text.toString().trim()
            val password = view!!.txt_password.text.toString().trim()

            if(TextUtils.isEmpty(username)) {
                context?.let { it1 -> CommonToast.show(it1,"请输入用户名") }
                return@setOnClickListener
            }
            if(TextUtils.isEmpty(password)) {
                context?.let { it1 -> CommonToast.show(it1,"请输入密码") }
                return@setOnClickListener
            }
            onLogin(username,password)
        }
    }

    /**
     * 登录
     */
    private fun onLogin(username:String,password: String) {
        val loginUrl = UrlConstants.BASE_URL + UrlConstants.URL_USER_LOGIN
        val mapHeader = HashMap<String,String>()
        val mapData = HashMap<String,String>()
        mapData["username"] = username
        mapData["password"] = password
        OkHttpProcessor.getInstance(context).postRequest(loginUrl, mapHeader, mapData, true, object: IHttpCallBack{
            override fun onStart() {
               (activity as MainActivity).showLoading()
            }

            override fun onSuccess(data: ResponseData?) {
                (activity as MainActivity).stopLoading()
                val loginBean = GsonUtil.parseJsonToBean(data!!.data.toString(), LoginBean::class.java)
                if(loginBean != null) {
                    SharedPreferenceManager.getInstance(context).save(SharePreferenceConstants.KEY_ISLOGIN,true)
                    SharedPreferenceManager.getInstance(context).save(SharePreferenceConstants.KEY_USERNAME,loginBean!!.username)
                }
                (activity as MainActivity).reLoadFragView()
            }

            override fun onFailed(code: Int, message: String?) {
                (activity as MainActivity).stopLoading()
                CommonToast.show(context,message);
            }

            override fun onHttpFailed(message: String?) {
                (activity as MainActivity).stopLoading()
                CommonToast.show(context,message)
            }

        })
    }
}